import { useMutation, useQuery } from "@apollo/client";
import {
  commitOrder_service,
  getOrdersByProduct_service, getOwnOrders_service,
} from "../../graphql/order";
import { OrderStatusType, OrderType } from "../../types/order";
import { resType } from "../../constant";

export const useFetchCreateOrder = () => {
  const [fun, { loading }] = useMutation(commitOrder_service);

  const createOrder = async (params: OrderType) => {
    const res = await fun({
      variables: {
        params,
      },
    });
    return res.data.commitorder as resType<OrderType>;
  };

  return { createOrder, loading };
};

export const useFetchEditOrder = () => {
  const [fun, { loading }] = useMutation(commitOrder_service);

  const editOrder = async (orderCode: string) => {
    const res = await fun({
      variables: {
        orderCode,
        params: {
          status: OrderStatusType.REFUND,
        },
      },
    });

    return res.data.commitorder as resType;
  };

  return { editOrder, loading };
};

export const useFetchGetOrdersByProduct = (productId: string) => {
  const { data, loading } = useQuery(getOrdersByProduct_service, {
    variables: {
      productId,
    },
    fetchPolicy: "network-only",
  });
  return { data: data?.getorderByProduct.data as OrderType[], loading } as {
    data: OrderType[];
    loading: boolean;
  };
};

export const useFetchGetOwnOrders = () => {
  const { data } = useQuery(getOwnOrders_service, {
    fetchPolicy: "network-only",
  });

  return { data: data?.getOrdersByUserId.data as OrderType[] } as {
    data: OrderType[];
  };
};
